//
//  ViewController.m
//  Homework_19
//
//  Created by 徐昊 on 16/8/9.
//  Copyright © 2016年 徐昊. All rights reserved.
//

#import "ViewController.h"
#import "CustomTableViewCell.h"
#import "carModel.h"
#import "UIImageView+WebCache.h"
#import "FirstTableViewCell.h"
#import "SecondTableViewCell.h"
#import "firstModel.h"

#define kTableViewCellName @"reuse"
#define kTableViewFirstCellName @"first"
#define kTableViewSecondCellName @"second"
@interface ViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSArray *carArr;
@property (nonatomic, strong) NSMutableArray *letterArr;
@property (nonatomic, strong) NSArray *list;
@property (nonatomic, strong) NSArray *secondList;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    [self handleData];
    [self handleData2];
//    [self handleData3];
    _tableView.tableFooterView = [UIView new];
}
- (void)handleData {
    _letterArr = [[NSMutableArray alloc] init];
    NSURL *imageURL = [NSURL URLWithString:@"http://app.api.autohome.com.cn/autov4.6/cars/brands-a2-pm2-v4.6.1-ts635580073583652962.html"];
    NSMutableURLRequest *imageURLRequest = [NSMutableURLRequest requestWithURL:imageURL];
    imageURLRequest.HTTPMethod = @"GET";
    NSURLResponse *response = nil;
    NSError *error = nil;
    NSData *data = [NSURLConnection sendSynchronousRequest:imageURLRequest returningResponse:&response error:&error];
    if (data) {
        NSError *error = nil;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
        _carArr = [[dic objectForKey:@"result"] objectForKey:@"brandlist"];
        for (NSDictionary *dic in _carArr) {
            NSString *str = [dic objectForKey:@"letter"];
            [_letterArr addObject:str];
        }
    }
    [_letterArr insertObject:@"热" atIndex:0];
    [_letterArr insertObject:@"主" atIndex:1];
}
- (void)handleData2 {
    NSURLSession *urlSession2 = [NSURLSession sharedSession];
    NSURL *imageURL = [NSURL URLWithString:@"http://223.99.255.20/cars.app.autohome.com.cn/dealer_v6.0.0/dealer/hotbrands-pm2.json%20HTTP/1.1"];
    NSMutableURLRequest *imageURLRequest = [NSMutableURLRequest requestWithURL:imageURL];
    imageURLRequest.HTTPMethod = @"GET";
    NSURLSessionDataTask *dataTask = [urlSession2 dataTaskWithRequest:imageURLRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            
            NSError *error = nil;
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
//            NSLog(@"%@", dic);
            NSDictionary *result = [dic objectForKey:@"result"];
            _list = [NSArray array];
            _list = [result objectForKey:@"list"];
            
            [_tableView reloadData];
        });
    }];
    // 让 dataTask 执行
    [dataTask resume];
    
}
- (void)handleData3 {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"Extension" ofType:@"json"];
    NSData *JSONData = [NSData dataWithContentsOfFile:path];
    NSError *error = nil;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableContainers error:&error];

    NSDictionary *result = [dic objectForKey:@"result"];
    _secondList = [NSArray array];
    _secondList = [result objectForKey:@"list"];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _carArr.count + 2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10;
}
-(NSArray <NSString *>*)sectionIndexTitlesForTableView:(UITableView *)tableView{
    
    return _letterArr;
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0 || section == 1) {
        return 1;
    } else {
        NSArray *arr = [_carArr[section - 2] objectForKey:@"list"];
        return arr.count;
    }
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return @"热门搜索";
    } else if (section == 1) {
        return @"主打车";
    }
    return _letterArr[section];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 200;
    } else if (indexPath.section == 1)
    {
        return 150;
    } else {
        return 50;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        FirstTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"first"];
        cell.array = _list;
        return cell;
    }
    if (indexPath.section == 1) {
        SecondTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"second"];
//        cell.array = _secondList;
        return cell;
    }
    CustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kTableViewCellName];
    NSDictionary *dic = [_carArr[indexPath.section - 2] objectForKey:@"list"][indexPath.row];
    carModel *model = [carModel carModelWithDictionary:dic];
    cell.label.text = model.name;
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:model.imgurl] placeholderImage:[UIImage imageNamed:@"@1"]];
    return cell;

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
